<template>
    <el-header class="header">
        <el-header class="header-inner">
            <div class="header-logo">
                <img src="@/assets/images/systemManagement/菜单.png" alt="菜单图标">
                <span>系统管理</span>
            </div>
            <div class="user-info">
                <img :src="imgUrl" alt="用户头像" class="user-avatar">
                <span>{{ userName }}</span>
            </div>
        </el-header>
    </el-header>
    <el-main class="main-container">
        <!-- 顶部操作栏 -->
        <el-row class="operation-bar" justify="end">
            <el-button type="danger" @click="handleAdd">
                <el-icon><Plus/></el-icon>添加
            </el-button>
            <el-button type="info" @click="handleRefresh">
                <el-icon><Refresh /></el-icon>刷新
            </el-button>
        </el-row>

        <!-- 组织架构表格 -->
        <el-table
            :data="tableData"
            style="width: 100%; margin-bottom: 20px"
            row-key="id"
            border
            default-expand-all
            :loading="tableLoading"
        >
            <el-table-column prop="name" label="组织名称" />
            <el-table-column prop="contactPerson" label="负责人姓名" />
            <el-table-column prop="contactPhone" label="负责人手机号" />
            <el-table-column prop="serviceNumber" label="服务商数量" />
            <el-table-column prop="equipmentNumber" label="设备数量" />
            <el-table-column prop="userNumber" label="用户数量" />
            <el-table-column prop="deliveriesNumber" label="投递次数" />
            <el-table-column prop="deliveryWeight" label="投递重量(KG)" />
            <el-table-column label="操作" width="120">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/编辑模态框 -->
        <el-dialog 
            v-model="dialogVisible" 
            align-center 
            :title="isEdit ? '编辑组织' : '新增组织'"  
            width="600px"
            :before-close="handleDialogClose"
        >
            <el-form 
                ref="formRef"  
                :model="form"  
                :rules="rules" 
                label-width="120px"
                class="dialog-form"
            >
                <!-- 父公司选择 -->
                <el-form-item label="上一级" prop="parentCompanyId">
                    <el-select 
                        placeholder="请选择上一级（根公司无需选择）" 
                        v-model="form.parentCompanyId" 
                        clearable
                        style="width: 100%"
                    >
                        <el-option 
                            v-for="item in parentOptions" 
                            :key="item.value" 
                            :label="item.label" 
                            :value="item.value" 
                        />
                    </el-select>
                </el-form-item>

                <!-- 组织名称 -->
                <el-form-item label="组织名称" prop="orgName">
                    <el-input 
                        placeholder="请输入组织名称" 
                        v-model="form.orgName" 
                        clearable
                        style="width: 100%"
                    />
                </el-form-item>

                <!-- 负责人姓名 -->
                <el-form-item label="负责人姓名" prop="leaderName">
                    <el-input 
                        placeholder="请输入负责人姓名" 
                        v-model="form.leaderName" 
                        clearable
                        style="width: 100%"
                    />
                </el-form-item>

                <!-- 负责人手机号 -->
                <el-form-item label="负责人手机号" prop="leaderPhone">
                    <el-input 
                        placeholder="请输入负责人手机号" 
                        v-model="form.leaderPhone" 
                        clearable
                        style="width: 100%"
                    />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSave" :loading="saveLoading">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </el-main>
</template>

<script setup>
import { ref, reactive, onMounted,watch } from 'vue';
import { Plus, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus'; 
import userAvatar from '@/assets/images/systemManagement/菜单.png';
import {getOrganization,updateOrganization,insertOrganization} from '@/components/DeviceMange/Organization'

// 基础状态
const imgUrl = ref(userAvatar);
const userName = ref("138****1234");
const dialogVisible = ref(false);
const formRef = ref(null);
const isEdit = ref(false);
const editId = ref('');
const tableLoading = ref(false);
const saveLoading = ref(false);

// 表单数据（语义化命名）
const form = reactive({
    parentCompanyId: '',   // 父公司ID（空表示根公司）
    orgName: '',           // 组织名称
    leaderName: '',        // 负责人姓名
    leaderPhone: '',        // 负责人手机号
    id:''
});

// 父公司选项（ID作为关联键）
const parentOptions = ref([{ label: '无（根公司）', value: '' }]);

// 表单验证规则（覆盖所有必填项）
const rules = reactive({
    orgName: [
        { required: true, message: '请输入组织名称', trigger: 'blur' }
    ],
    leaderName: [
        { required: true, message: '请输入负责人姓名', trigger: 'blur' }
    ],
    leaderPhone: [
        { required: true, message: '请输入负责人手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
    ]
});


// 组织架构数据源（带parentId明确父子关系）
const tableData = ref([]);

let getOrganizationList=()=>{
    getOrganization()
    .then(res=>{
        console.log(res.dataset);
        tableData.value = res.dataset
    })
    // generateParentCompanyOptions()
}

// 生成父公司选项（ID作为value）
watch(
  () => tableData.value,
  (newVal) => {
    const rootCompanies = newVal.map(item => ({
      label: item.name || '未知名称',
      value: item.id
    }));
    parentOptions.value = [
      { label: '无（根公司）', value: 0 },
      ...rootCompanies
    ];
  },
  { immediate: true } // 初始加载时执行一次
);

// 初始化父公司选项
onMounted(() => {
    getOrganizationList()
});

// 打开新增模态框
const handleAdd = () => {
    resetForm();
    isEdit.value = false;
    dialogVisible.value = true;
};

// 打开编辑模态框（回显数据）
const handleEdit = (row) => {
    isEdit.value = true;
    editId.value = row.id;
    dialogVisible.value = true;

    // 回显父公司ID（转字符串避免类型问题）

    form.parentCompanyId = "";
    form.orgName = row.name;
    form.leaderName = row.contactPerson;
    form.leaderPhone = row.contactPhone;
    form.id = row.id

    // 清除验证状态
    formRef.value?.clearValidate();
};

// 保存表单（新增/编辑通用）
const handleSave = async () => {
    const formInstance = formRef.value;
    if (!formInstance) return;

    // 表单验证
    const valid = await formInstance.validate().catch(() => false);
    if (!valid) return;

    saveLoading.value = true;
    try {
        if (isEdit.value) {
            // 编辑逻辑：递归更新节点
            console.log(isEdit.value);
            // console.log(form);
            let data ={
                id:form.id,
                contactPhone:form.leaderPhone,
                contactPerson:form.leaderName,
                parentId:form.parentCompanyId==''?0:form.parentCompanyId,
                name:form.orgName
            } 
            updateOrganization(data)
            .then(res=>{
                if(res.code==200){
                    ElMessage({
                        message: '编辑成功',
                        type: 'success',
                    })
                    getOrganizationList()
                }else{
                    ElMessage({
                        message: '编辑失败',
                        type: 'error',
                    })
                }
            })
            
        } else {
            console.log(form);
            let data = {
                parentId:form.parentCompanyId,
                contactPhone:form.leaderPhone,
                contactPerson:form.leaderName,
                name:form.orgName
            }
            console.log(data);
            
            insertOrganization(data)
            .then(res=>{
                if(res.code==200){
                    ElMessage.success('新增成功！');
                    getOrganizationList()
                }
                else{
                    ElMessage.error('新增失败！');
                }
            })
        }

        // 刷新父公司选项（组织架构可能变化）
        // generateParentCompanyOptions();
        // 关闭模态框并重置
        dialogVisible.value = false;
        resetForm();
    } catch (error) {
        ElMessage.error(`操作失败：${error.message || '未知错误'}`);
    } finally {
        saveLoading.value = false;
    }
};

// 刷新表格（模拟接口请求）
const handleRefresh = async () => {
    tableLoading.value = true;
    try {
        await new Promise(resolve => setTimeout(resolve, 500));
        ElMessage.success('表格已刷新！');
    } catch (error) {
        ElMessage.error('刷新失败，请重试！');
    } finally {
        tableLoading.value = false;
    }
};

// 重置表单
const resetForm = () => {
    formRef.value?.resetFields();
    form.parentCompanyId = '';
    form.orgName = '';
    form.leaderName = '';
    form.leaderPhone = '';
    isEdit.value = false;
    editId.value = '';
};

// 模态框关闭回调（防止未保存数据丢失）
const handleDialogClose = () => {
    ElMessageBox.confirm('确认关闭？未保存内容将丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        resetForm();
        dialogVisible.value = false;
    }).catch(() => {});
};
</script>

<style lang="less" scoped>
.header {
    background: #fff;
    height: 80px;
    border-bottom: 1px solid #e5e7eb;
    box-shadow: 0 1px 2px rgba(0,0,0,0.05);

    .header-inner {
        height: 60%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #e5e7eb; 
        padding: 0 20px;

        .header-logo {
            display: flex;
            align-items: center;
            gap: 8px;

            img { width: 24px; height: 24px; }
            span { font-size: 18px; font-weight: 500; }
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-right: 20px;

            .user-avatar { width: 32px; height: 32px; border-radius: 50%; }
            span { font-size: 14px; color: #666; }
        }
    }
}

.main-container {
    padding: 24px;
}

.operation-bar {
    margin-bottom: 20px;
    gap: 10px;
}

.dialog-form {
    padding: 20px;
}

.dialog-footer {
    text-align: right;
    gap: 10px;
}

.el-input, .el-select {
    width: 100%; // 自适应父容器
}
</style>